package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.R;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.ISysUserService;
import com.itheima.ydd.service.IYddUserService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/home")
@RestController
@Slf4j
public class SysHomeController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IYddUserService yddUserService;

    @PostMapping("/index/login")
    public R login(@RequestBody YddUser yddUser){
        log.info("登陆用户：{}",yddUser.toString());

        String mobile = yddUser.getMobile();
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile, mobile);
        YddUser one = yddUserService.getOne(wrapper);

        if (one == null){
            return R.error("账号不存在");
        }

        String password = yddUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))){
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();
           /* String roleId = one.getRoleId()
                    .replace("[","")
                    .replace("]", "")
                    .replace("\"", "");*/

            tokenMap.put("userId", one.getId());
//            tokenMap.put("roleId", roleId);
            tokenMap.put("mobile",one.getMobile());
            String token = JwtUtils.getToken(tokenMap);

            retMap.put("token", token);
            return R.success("token", JwtUtils.getToken(tokenMap));
        }
        return R.error("密码错误");

    }
    /** md5加密
     * @param password 密码
     */
    private String generatePassword(String password){
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
}